<template>
  <div>
    <div id="main" style="height: 100vh; width: 100vw"></div>
  </div>
</template>

<script>
import axios from "axios";
import * as echarts from "echarts";
import "echarts-gl";
import worldJson from '@/assets/world.json';
import $ from "jquery";
import { useRoute } from "vue-router";

export default {
  data() {
    return {
      visited_areas: [],
      mapChart: null,
    };
  },
  setup() {
    const router = useRoute();
    return {
      router,
    };
  },
  methods: {
    handleMouseWheel(event) {
      this.mapChart.resize();
    },
    handleMapClick(params) {
      // window.location.href = `/China?area=${params.name}&id=1`;
      console.log('Map clicked:', params.name);
      this.$router.push({
        path: '/China',
        query: {
          area: params.name,
          id: 1
        }
      });
    },
    async loadAreas() {
      try {
        const token = localStorage.getItem('token');
        const response = await axios.get(
          "http://localhost:8006/api/visited_areas",
          {
            headers: {
              'Authorization': `Bearer ${token}`
            }
          }
        );

        this.visited_areas = response.data;

      } catch (error) {
        if (error.response && error.response.status === 401) {
          // token无效或过期，重定向到登录页
          this.$router.push('/login');
        }
        console.error("Error loading visited areas:", error);
      }
    },
    setMapOption(data) {
      echarts.registerMap("world", data);
      const canvas = document.createElement("canvas");
      console.error("Error loading visited_datas:", this.visited_areas);

      const visited_datas = this.visited_areas.map((visited_area) => ({
        name: visited_area,
        itemStyle: { areaColor: "yellow" }, // 设置填充色为黄色
      }));

      this.mapChart = echarts.init(canvas, null, {
        // devicePixelRatio: dpr,     // 添加该参数即可
        devicePixelRatio: 2, // 添加该参数即可
        width: 2048,
        height: 1024,
      });
      this.mapChart.setOption({
        backgroundColor: "rgba(3, 52, 93,.9)",
        geo: {
          type: "map",
          map: "world",
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          boundingCoords: [
            [-180, 90],
            [180, -90],
          ],
          itemStyle: {
            borderWidth: 10,
            normal: {
              borderColor: "rgba(255,255,255,0.7)",
              areaColor: "rgba(0, 90, 171, 1)",
              label: {
                show: false,
              },
            },
          },
          emphasis: {
            itemStyle: {
              areaColor: "#602bdd",
              borderColor: "#f29100",
            },
          },
        },
        series: [
          {
            type: "scatter",
            coordinateSystem: "geo",
            label: { show: true },
            data: [
              {
                value: [103.012761, 33.113421],
                label: {
                  color: "rgba(25, 228, 253, 1)",
                  fontSize: 12,
                  fontWeight: "bold",
                  formatter: "爱你一万年",
                },
              },
            ],
          },
          {
            type: "map",
            map: "world",
            itemStyle: {
              normal: {
                areaColor: "rgba(0, 90, 171, 1)", // 其他地区颜色
              },
              emphasis: {
                areaColor: "#602bdd",
              },
            },
            data: visited_datas,
          },
        ],
      });
      this.mapChart.on("click", (params) => {
        console.log("params", params);
        this.$router.push({ path: '/China', query: { area: params.name, id: 1 } });
      });
    },
    setGlobeOption() {
      const globeChart = echarts.init(document.getElementById("main"));

      globeChart.setOption({
        globe: {
          baseTexture: this.mapChart,
          shading: "realistic",

          realisticMaterial: {
            roughness: 0.7,
            metalness: 0.5,
          },
          light: {
            ambient: {
              intensity: 0.6,
            },
            main: {
              intensity: 1,
              shadow: true,
            },
          },
          postEffect: {
            enable: true,
            bloom: 10,
          },
          viewControl: {
            center: [0, 0, 0],
            alpha: 20,
            beta: 50,
            autoRotate: true,
            autoRotateAfterStill: 3,
            distance: 200,
            autoRotateSpeed: 15,
          },
        },
      });
    },
  },

  async mounted() {
    await this.loadAreas(); // 等待 loadAreas 完成
    this.setMapOption(worldJson);
    this.setGlobeOption();
    $(document).on("mousewheel DOMMouseScroll", this.handleMouseWheel);
    this.mapChart.on("click", this.handleMapClick);
  },
};
</script>

<style scoped>
/* 添加样式 */
html,
body {
  width: 100%;
  height: 100%;
  overflow: hidden;
  color: #602bdd;
  background-color: rgba(0, 0, 0, 0.8);
}
</style>
